import axios from "axios";
import {ElMessage} from "element-plus";
import {useTokenStore} from "@/stores/tokenStore";
import router from "@/router";

/* 创建新的 axios 实例 */
const request = axios.create({
    baseURL: import.meta.env.VITE_APP_BASE_API
})

/* 请求拦截器 */
request.interceptors.request.use(config => {
    const tokenStore = useTokenStore()
    config.headers['Authorization'] = tokenStore.accessToken
    return config
}, e => {
    return Promise.reject(e)
})

/* 设置响应拦截器 */
request.interceptors.response.use(resp => {
    const {code, message, data} = resp.data

    if (code == 200) {
        // 返回调用处直接返回的ResultVO中的data 返回调用的地方(then(data))
        return Promise.resolve(data)
    }else if(code == 403){
        ElMessage.error(message)
        const tokenStore = useTokenStore()
        tokenStore.clearToken()
        router.push('/login')
        return Promise.reject(message)
    } else {
        ElMessage.error(message)
        return Promise.reject(message)
    }
}, e => {
    console.log(e)
    return Promise.reject(e)
})

export default request